'use strict'

const Controller = require('egg').Controller
const Joi = require('joi')
const _ = require('lodash')
const uuidv4 = require('uuid/v4')
const path = require('path')

class MinaIndexController extends Controller {

    // 上传驾照图片
    async UploadImage() {
        const { ctx, service } = this
        const joi_schema = Joi.object().keys({
            module: Joi.string().valid(['DrivingLice', 'Review']).required(),
            source: Joi.string().required(),
        })
        let joi_validate = Joi.validate(ctx.request.body, joi_schema)
        if(joi_validate.error){
            ctx.invalid(joi_validate.error)
            return
        }
        let params = joi_validate.value
        try {
            let pathDir = `public/upload/${ params.module }`
            let file = `${ uuidv4() }.png`
            const { b64Img } = ctx.helper
            await b64Img.transform(params.source, pathDir, file)
            ctx.success(path.join(pathDir, file))
        } catch (err) {
            ctx.fail(err)
        }
    }

    // 查询所有服务城市
    async FindCity() {
        const { ctx, service } = this
        ctx.success(await service.minaCity.findAll())
    }

    // 查询单个服务城市及镇区
    async ViewCity() {
        const { ctx, service } = this
        const joi_schema = Joi.object().keys({
            minaCityId: Joi.string(),
            name: Joi.string(),
            postalCode: Joi.string(),
            phoneCode: Joi.string(),
        })
        .or('minaCityId', 'name', 'postalCode', 'phoneCode')
        let joi_validate = Joi.validate(ctx.request.body, joi_schema)
        if(joi_validate.error){
            ctx.invalid(joi_validate.error)
            return
        }
        let params = joi_validate.value
        try {
            let minaCity
            if(!_.isEmpty(params.minaCityId)){
                params.id = params.minaCityId
                params = _.omit(params, ['minaCityId'])
            }
            minaCity = await service.minaCity.findOne(params)
            ctx.success(minaCity)
        } catch (err) {
            ctx.fail(err)
        }
    }


}

module.exports = MinaIndexController